package com.ruoyi.report.service.test.impl;

import com.ruoyi.report.domain.test.HanZaiChildren;
import com.ruoyi.report.mapper.test.HanZaiChildrenMapper;
import com.ruoyi.report.service.test.HanZaiChildrenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: 憨憨爱崽崽
 * Name: HanZaiChildrenServiceImpl
 * Date: 2022/4/22
 * Time: 20:36
 **/
@Service
public class HanZaiChildrenServiceImpl implements HanZaiChildrenService {
    @Autowired
    HanZaiChildrenMapper childrenMapper;
    @Override
    public List<HanZaiChildren> selectChildren() {
        List<HanZaiChildren> hanZaiChildren = childrenMapper.selectChildren();
        List<HanZaiChildren> treeList = toChildren(hanZaiChildren, 0);
        List<HanZaiChildren> userChildren = userChildren(treeList);
        return userChildren;
    }
    private  List<HanZaiChildren> userChildren(List<HanZaiChildren> treeList){
        for (HanZaiChildren tree : treeList){
            if (tree.getChildren() == null){
                List<HanZaiChildren> userChildren = childrenMapper.selectUserByDeptId(tree.getDeptId());
                tree.setChildren(userChildren);
            }else{
                userChildren(tree.getChildren());
            }
        }
        return treeList;
    }
    private static List<HanZaiChildren> toChildren(List<HanZaiChildren> treeList,Integer pid){
        List<HanZaiChildren> resultChildren = new ArrayList<HanZaiChildren>();
        for (HanZaiChildren children : treeList){
            if (pid.equals(children.getValue())){
                resultChildren.add(findChildren(children,treeList));
            }
        }
        return resultChildren;
    }
    private static HanZaiChildren findChildren(HanZaiChildren hanZaiChildren,List<HanZaiChildren> treeList){
        for (HanZaiChildren tree : treeList){
            if (hanZaiChildren.getDeptId().equals(tree.getValue())){
                if (hanZaiChildren.getChildren() == null){
                    hanZaiChildren.setChildren(new ArrayList<>());
                }
                hanZaiChildren.getChildren().add(findChildren(tree, treeList));
            }
        }
        return hanZaiChildren;
    }
}
